package main

import (
	"context"
	"example_1/bridge"
	"strings"
)

var alertFactory *bridge.AlertFactory
var alertFactory2 *bridge.AlertFactory2

func main() {
	initNotifyAndAlert()
	alertNotify(context.Background(), "error")
}

func alertNotify(ctx context.Context, message string) error {
	notifyInfo, _ := bridge.NewNotifyInfoBuilder().
		SetUserName("yjt").
		SetEmail("yjt@163.com").
		SetPhone("18845165087").
		SetWechatID("ghtregrtea").
		SetWechatGroupID("gewwafsgrgegs").
		SetMessage(message).Build()

	var alert bridge.AlertInterface
	var err error

	switch {
	case strings.Contains(message, "panic"):
		alert, err = alertFactory2.Create("urgencyAlert")
	case strings.Contains(message, "error"):
		alert, err = alertFactory2.Create("normalAlert")
	case strings.Contains(message, "warning"):
		alert, err = alertFactory2.Create("trivialAlert")
	default:
		return nil
	}

	if err != nil {
		return err
	}
	return alert.Alert(ctx, *notifyInfo)
	//if strings.Contains(message, "panic") {
	//	alert, _ := alertFactory.CreateAlert("urgencyAlert")
	//	return alert.Alert(ctx, *notifyInfo)
	//}
	//if strings.Contains(message, "error") {
	//	alert, _ := alertFactory.CreateAlert("normalAlert")
	//	return alert.Alert(ctx, *notifyInfo)
	//}
	//if strings.Contains(message, "warning") {
	//	alert, _ := alertFactory.CreateAlert("trivialAlert")
	//	return alert.Alert(ctx, *notifyInfo)
	//}
	//
	//return nil
}

func initNotifyAndAlert() {
	phoneNotify := bridge.NewPhoneNotify()
	emailNotify := bridge.NewEmailNotify()
	messageNotify := bridge.NewMessageNotify()
	wechatNotify := bridge.NewWechatNotify()
	wechatGroupNotify := bridge.NewWechatGroupNotify()

	//alertMap := map[string]bridge.AlertInterface{
	//	"urgencyAlert": bridge.NewUrgencyAlert(emailNotify, phoneNotify),
	//	"normalAlert":  bridge.NewNormalAlert(wechatNotify, emailNotify, messageNotify),
	//	"trivialAlert": bridge.NewTrivialAlert(wechatNotify, wechatGroupNotify),
	//}
	//alertFactory = bridge.NewAlertFactory(alertMap)

	// 注册式工厂模式，支持动态注册（这里使用func bridge.AlertInterface,每次create时候都直接初始化，而不是使用缓存）
	alertFactory2 = bridge.NewAlertFactory2()
	alertFactory2.Register("urgencyAlert", func() bridge.AlertInterface {
		return bridge.NewUrgencyAlert(emailNotify, phoneNotify)
	})
	alertFactory2.Register("normalAlert", func() bridge.AlertInterface {
		return bridge.NewNormalAlert(wechatNotify, emailNotify, messageNotify)
	})
	alertFactory2.Register("trivialAlert", func() bridge.AlertInterface {
		return bridge.NewTrivialAlert(wechatNotify, wechatGroupNotify)
	})
}
